package cn.vshare.chat;


import cn.vshare.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;

@RestController
@ServerEndpoint("/chat/{myId}/{fId}")
public class ChatController {
    private Session session;
   // private HttpSession httpSession;
   // private ServletContext application;
    private String key;
   // key=myId+"to"+fId
    @OnOpen
    public void onOpen(@PathParam("myId") String myId, @PathParam("fId") String fId, Session session){
        this.session=session;
       // this.httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
     //   String myId=( (User) httpSession.getAttribute("USER")).getId();
        key=myId+"to"+fId;
        UserPool.addOnlineUser(key,session);
        System.out.println("建立连接");
    }
    //    myid,fid/message  信息的格式
    @OnMessage
    public  void onMessage(String message) throws IOException {
        String[] strs1=message.trim().split(",");
        String myId=strs1[0].trim();
        String[] fidMess=strs1[1].trim().split("/");
        String fId=fidMess[0].trim();
        String mess=fidMess[1].trim();
        String key=fId+"to"+myId;
        Session session1=UserPool.onlineUserPool.get(key);
        if (session1!=null){
            session1.getBasicRemote().sendText(mess);
        }else {
            String words=fId+","+myId+"/"+mess;
            UserPool.addOutlineMessage(words);
        }

    }
    @OnClose
    public void onClose(){
        UserPool.removeOutLineUser(key);
        System.out.println(key+"退出聊天");
    }

    @RequestMapping("getOutLineFidMessage")
    public List<String> getOutLineFidMessage(String myId,String fId){
        List<String> messageList=UserPool.getOutlineMessageByFriendId(myId,fId);
        return messageList;
    }
    @RequestMapping("getOutlineMessageCountByFid")
    public int getOutlinMessageCountByFid(String myId,String fId){
        return UserPool.getOutlineMessageCountByFriendId(myId, fId);
    }
    @RequestMapping("/getAllOutLineMessageCountById")
    public int  getAllOutLineMessageCountById(HttpSession httpSession){
        User user= (User) httpSession.getAttribute("USER");
        String myId=user.getId();
        return UserPool.getAllOutLineMessageCountById(myId);
    }

    @RequestMapping("/toChatRoom")
    public ModelAndView toChatRoom(){
        return new ModelAndView("chatRoom");
    }








}
